#!/bin/bash

set -e

# 配置变量
MINIO_USER="${MINIO_ROOT_USER}"
MINIO_PASS="${MINIO_ROOT_PASSWORD}"

# 从.env文件读取配置
source .env
IFS=',' read -ra SERVERS <<< "$SERVERS_IP"
IFS=',' read -ra DATA_DIRS <<< "$DATA_DIRS"

# 数据目录权限
setup_data_dirs() {
    for dir in "${DATA_DIRS[@]}"; do
        chown -R 1000:1000 "$dir"
        chmod 777 "$dir"
    done
}

# 替换IP地址到docker-compose.yml
update_compose_file() {
    # 构建命令中的服务器列表
    local server_list=""
    for server in "${SERVERS[@]}"; do
        for dir in "${DATA_DIRS[@]}"; do
            if [ -z "$server_list" ]; then
                server_list="http://$server$dir"
            else
                server_list="$server_list http://$server$dir"
            fi
        done
    done

    # 更新docker-compose.yml中的command字段
    sed -i "s|server --console-address|server $server_list --console-address|" docker-compose.yml
}

# 启动MinIO服务
start_minio() {
    echo "Starting MinIO service..."
    docker-compose up -d
    sleep 10

    # 检查服务状态
    if docker-compose ps | grep -q "Up"; then
        echo "MinIO service started successfully on $(hostname)"
    else
        echo "Failed to start MinIO service"
        exit 1
    fi
}

# 主函数
main() {
    echo "Starting MinIO distributed cluster setup..."

    setup_data_dirs
    update_compose_file
    start_minio

    echo "MinIO cluster setup completed on $(hostname)"
    echo "Console URL: http://$(hostname -I | awk '{print $1}'):9001"
    echo "Access Key: $MINIO_USER"
    echo "Secret Key: $MINIO_PASS"
}

main "$@"
